<template>
  <el-header class="header-bar">
    <div class="header-left">
      <el-logo class="logo">
        <img src="/logo.ico" alt="Logo" />
        <span class="logo-text">桂林网顺网业管理有限公司</span>
      </el-logo>
      <el-menu
        :default-active="currentRoute"
        mode="horizontal"
        :ellipsis="false"
        background-color="transparent"
        active-text-color="#ffd04b"
        class="menu"
        @select="handleMenuSelect"
      >
        <!-- 动态生成主菜单 -->
        <template v-for="route in mainRoutes" :key="route.path">
          <!-- 没有子路由的时候 -->
          <el-menu-item v-if="!hasSubItem(route)" :index="route.path">
            {{ route.meta?.title || route.name }}
          </el-menu-item>
          <!-- 有子路由的时候 -->
          <el-sub-menu v-else :index="route.path">
            <template #title>
              <span>{{ route.meta?.title || route.name }}</span>
            </template>
            <template v-for="subItem in getSubItems(route)" :key="subItem.path">
              <el-menu-item :index="subItem.path">
                {{ subItem.meta?.title || subItem.name }}
              </el-menu-item>
            </template>
          </el-sub-menu>
        </template>
      </el-menu>
    </div>

    <!-- 右边登录 -->
    <div class="header-right">
      <el-dropdown>
        <span class="user-info">
          <el-avatar :size="32">
            <img src="/default-avatar.jpg" alt="用户头像" />
          </el-avatar>
          <span class="user-name">管理员</span>
          <el-icon class="el-icon--right"><ArrowDown /></el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>个人信息</el-dropdown-item>
            <el-dropdown-item>修改密码</el-dropdown-item>
            <el-dropdown-item divided>退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <el-button type="text" size="small" class="header-btn">
        <el-icon><Bell /></el-icon>
      </el-button>
    </div>
  </el-header>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { ArrowDown, Bell } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

// 存储所有符合菜单显示条件的路由（仅初始化时计算一次）
const validRoutes = ref<RouteRecordRaw[]>([])
// 存储主路由（顶级路由，已排序）
const mainRoutes = ref<RouteRecordRaw[]>([])
// 存储子路由映射：key为父路由path，value为子路由数组（已排序）
const subRoutesMap = ref<Record<string, RouteRecordRaw[]>>({})

// 判断路由是否应该在菜单中显示（纯逻辑判断，无重复计算）
const shouldShowInMenu = (route: RouteRecordRaw): boolean => {
  return route.meta?.showInHeaderMenu !== false
    && !!route.meta?.title
    && !!route.name
    && !route.path.includes(':') // 排除带参数的路由
    && !route.redirect // 排除重定向路由
}

// 初始化：一次性处理所有路由，缓存结果
onMounted(() => {
  // 1. 筛选所有符合条件的路由（只执行一次）
  validRoutes.value = router.getRoutes().filter(route => shouldShowInMenu(route))

  // 2. 筛选主路由（顶级路由）并排序
  mainRoutes.value = validRoutes.value
    .filter(route => {
      const parent = route.meta?.parent as string
      // 顶级路由：无父路由，或父路由为''/'
      return !parent || ['', '/'].includes(parent)
    })
    .sort((a, b) => {
      const orderA = typeof a.meta?.order === 'number' ? a.meta.order : 999;
      const orderB = typeof b.meta?.order === 'number' ? b.meta.order : 999;
      return orderA - orderB;
    })

  // 3. 从有效路由中提取所有 “有明确非顶级父路由” 的子路由，并按父路由路径归类
  subRoutesMap.value = validRoutes.value.reduce((map, parentRoute) => {
    const parentPath = parentRoute.path as string;
    // 过滤顶级父路由（空路径或根路径）
    if (parentPath && !['', '/'].includes(parentPath)) {
      if (parentRoute.children && parentRoute.children.length > 0) {
        if (!map[parentPath]) {
          map[parentPath] = [];
        }
        const processedChildren = parentRoute.children.map(child => {
          const childPath = child.path.replace(/^\//, '');
          return { ...child, path: `${parentPath}/${childPath}` };
        });
        map[parentPath].push(...processedChildren);
      }
    }
    return map;
  }, {} as Record<string, RouteRecordRaw[]>)


  // 对子路由数组排序（只执行一次）
  Object.values(subRoutesMap.value).forEach(subRoutes => {
    subRoutes.sort((a, b) => {
      const orderA = typeof a.meta?.order === 'number' ? a.meta.order : 999;
      const orderB = typeof b.meta?.order === 'number' ? b.meta.order : 999;
      return orderA - orderB;
    });
  })
})

// 判断路由是否有子路由（直接从缓存映射中判断）
const hasSubItem = (route: RouteRecordRaw): boolean => {
  return (subRoutesMap.value[route.path]?.length || 0) > 0
}

// 获取子路由（直接从缓存映射中获取）
const getSubItems = (parentRoute: RouteRecordRaw): RouteRecordRaw[] => {
  return subRoutesMap.value[parentRoute.path] || []
}

// 菜单选择事件
const handleMenuSelect = (path: string) => {
  router.push(path)
}

// 当前路由路径
const currentRoute = ref(route.path)
// 监听路由变化，更新当前激活的菜单
route.path && (currentRoute.value = route.path)
router.afterEach((to) => {
  currentRoute.value = to.path
})
</script>

<style scoped>
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: transparent;
  padding: 0 20px;
  height: 80px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  margin-right: 80px;
}

.logo img {
  height: 40px;
  margin-right: 10px;
}

.logo-text {
  color: #333333;
  font-size: 18px;
  font-weight: bold;
}

.menu {
  background-color: transparent !important;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  margin-right: 20px;
}

.user-name {
  margin-left: 8px;
  margin-right: 4px;
}

.header-btn {
  color: #333;
  font-size: 18px;
}

.header-btn:hover {
  color: #ffd04b;
}
</style>
